<?php


namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\BookCatalog;
use App\Models\BookCatalogPdf;
use App\Models\BookTitle;
use App\Models\PhotoArchives;
use App\Models\PhotoCatalog;
use App\Models\PhotoCatalogImage;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class BaseService
{
    public $host;

    public function __construct()
    {
        $this->host = config('site.domain');
    }

    /**
     * 获取变化后的序号
     * $now  当前序号
     * $needUpdates 要发生变化的序号 数组
     * 获取变化后的序号
     */
    public function getNewSerialNo($now, $delSerialNos)
    {
        $nowSerialNo = $now;
        $newSerialNo = $now;
        foreach ($delSerialNos as $value) {
            if ($nowSerialNo > $value) {
                $newSerialNo = $newSerialNo - 1;
            }
        }
        return $newSerialNo;
    }

    /**
     * 判断序号是否连续并从1递增，序号不符合要求，导出的卷内会出错
     * $serialNos : 一维数组
     */
    public function checkSerialNo($serialNos)
    {
        if (min($serialNos) != 1) {
            return false;
        }
        if (max($serialNos) != count($serialNos)) {
            return false;
        }
        if (sort($serialNos) != $serialNos) {
            return false;
        }
        if (array_unique($serialNos) != $serialNos) {
            return false;
        }

        return true;
    }

    /**
     * 有3种情况
     * $pageNum1：数字，$pageNum2：数字
     * $pageNum1：数字，$pageNum2：30~40
     * $pageNum1：30~40，$pageNum2：数字
     */
    public function comparePageNum($pageNum1, $pageNum2)
    {
        if (is_numeric($pageNum1) && is_numeric($pageNum2)) {
            if (to_int($pageNum1) > to_int($pageNum2)) {
                return false;
            }
        }
        if (is_numeric($pageNum1) && !is_numeric($pageNum2)) {
            $page = PhotoCatalogService::checkPageNum($pageNum2);
            if (!$page || ($pageNum1 > $page['small_page'])) {
                return false;
            }
        }
        if (!is_numeric($pageNum1) && is_numeric($pageNum2)) {
            $page = PhotoCatalogService::checkPageNum($pageNum1);
            if (!$page || ($page['big_page'] > $pageNum2)) {
                return false;
            }
        }

        return true;
    }

    /**
     * 格式化序号
     * $serialNo : 需要的序号
     * $zeroNum : 前导0的数量，例如   01、001、0001
     */
    public function formatSerialNo($serialNo, $zeroCount = 3)
    {
        if (!is_numeric($serialNo)) {
            return $serialNo;
        }
        $serialNo = (int)$serialNo;
        $len      = strlen($serialNo);

        if ($zeroCount == 3) {
            switch ($len) {
                case 1:
                    $serialNo = '000' . $serialNo;
                    break;
                case 2:
                    $serialNo = '00' . $serialNo;
                    break;
                case 3:
                    $serialNo = '0' . $serialNo;
                    break;
                default:
                    $serialNo = (int)$serialNo;
            }
        } elseif ($zeroCount == 2) {
            switch ($len) {
                case 1:
                    $serialNo = '00' . $serialNo;
                    break;
                case 2:
                    $serialNo = '0' . $serialNo;
                    break;
                default:
                    $serialNo = (int)$serialNo;
            }
        } elseif ($zeroCount == 1) {
            switch ($len) {
                case 1:
                    $serialNo = '0' . $serialNo;
                    break;
                default:
                    $serialNo = (int)$serialNo;
            }
        } else {
            $serialNo = (int)$serialNo;
        }

        return (string)$serialNo;
    }

    /**
     * 科技档案 获取【案卷】表实例
     *
     * @param $partCompanyId
     * @param $projectClassifyId
     * @return BookTitle
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 14:47
     */
    public function getBookTitleInstance($partCompanyId, $projectClassifyId) : BookTitle
    {
        if (empty($partCompanyId) || empty($projectClassifyId)) {
            throw new ApiException('缺少必要参数！');
        }
        $table = "book_titles_{$partCompanyId}_{$projectClassifyId}";
        if (!Schema::hasTable($table)) {
            DB::update("create table if not exists {$table}   like book_titles");
        }
        $bookCatalog = new BookTitle();

        return $bookCatalog->setTable($table);
    }

    /**
     * 科技档案 获取【卷内】表实例
     *
     * @param $partCompanyId
     * @param $projectClassifyId
     * @return BookCatalog
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 10:29
     */
    public function getBookCatalogInstance($partCompanyId, $projectClassifyId) : BookCatalog
    {
        if (empty($partCompanyId) || empty($projectClassifyId)) {
            throw new ApiException('缺少必要参数！');
        }
        $table = "book_catalogs_{$partCompanyId}_{$projectClassifyId}";
        if (!Schema::hasTable($table)) {
            DB::update("create table if not exists {$table} like book_catalogs");
        }
        $bookCatalog = new BookCatalog();

        return $bookCatalog->setTable($table);
    }

    /**
     * 科技档案 获取【卷内 pdf】表实例
     *
     * @param $partCompanyId
     * @param $projectClassifyId
     * @return BookCatalogPdf
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 10:30
     */
    public function getBookCatalogPdfInstance($partCompanyId, $projectClassifyId) : BookCatalogPdf
    {
        if (empty($partCompanyId) || empty($projectClassifyId)) {
            throw new ApiException('缺少必要参数！');
        }
        $table = "book_catalog_pdfs_{$partCompanyId}_{$projectClassifyId}";
        if (!Schema::hasTable($table)) {
            DB::update("create table if not exists {$table}   like book_catalog_pdfs");
        }
        $catalogPdf = new BookCatalogPdf();

        return $catalogPdf->setTable($table);
    }

    /**
     * 照片档案 获取【案卷】表实例
     *
     * @param $partCompanyId
     * @param $photoClassifyId
     * @return PhotoArchives
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 15:17
     */
    public function getPhotoArchiveInstance($partCompanyId, $photoClassifyId) : PhotoArchives
    {
        if (empty($partCompanyId) || empty($photoClassifyId)) {
            throw new ApiException('缺少必要参数！');
        }
        $table = "photo_archives_{$partCompanyId}_{$photoClassifyId}";
        if (!Schema::hasTable($table)) {
            DB::update("create table if not exists {$table}  like photo_archives");
        }
        $photoArchive = new PhotoArchives();

        return $photoArchive->setTable($table);
    }

    /**
     * 照片档案 获取【卷内】表实例
     *
     * @param $partCompanyId
     * @param $photoClassifyId
     * @return PhotoCatalog
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 15:14
     */
    public function getPhotoCatalogInstance($partCompanyId, $photoClassifyId) : PhotoCatalog
    {
        if (empty($partCompanyId) || empty($photoClassifyId)) {
            throw new ApiException('缺少必要参数！');
        }
        $table = "photo_catalogs_{$partCompanyId}_{$photoClassifyId}";
        if (!Schema::hasTable($table)) {
            DB::update("create table if not exists {$table} like photo_catalogs");
        }
        $bookCatalog = new PhotoCatalog();

        return $bookCatalog->setTable($table);
    }

    /**
     * 照片档案 获取【卷内照片】表实例
     *
     * @param $partCompanyId
     * @param $photoClassifyId
     * @return PhotoCatalogImage
     * @throws ApiException
     * @author: lxk
     * @date: 2024-09-12 10:23
     */
    public function getPhotoCatalogImageInstance($partCompanyId, $photoClassifyId) : PhotoCatalogImage
    {
        if (empty($partCompanyId) || empty($photoClassifyId)) {
            throw new ApiException('缺少必要参数！');
        }
        $table = "photo_catalog_images_{$partCompanyId}_{$photoClassifyId}";
        if (!Schema::hasTable($table)) {
            DB::update("create table if not exists {$table} like photo_catalog_images");
        }
        $photoCatalogImage = new PhotoCatalogImage();

        return $photoCatalogImage->setTable($table);
    }

    /**
     * 回收站的列表数据
     * 追加查询条件并格式化删除时间
     */
    public function formatRecycleData($request, $thisQuery)
    {
        if ($request->filled('del_date')) { //删除日期
            $delDate = $request->input('del_date');
            $thisQuery->whereDate('deleted_at', $delDate);
        }
        $perPage = config('site.limit') ?: 15;
        $list = $thisQuery->paginate($perPage);

        return $list->isNotEmpty() ? $list->toArray() : [];
    }

    /**
     * 判断文件合法性
     */
    public function isFileValid($request)
    {
        if (!$request->hasFile('file')) {
            throw new ApiException('请导入文件');
        }
        $file = $request->file('file'); //获取上传的文件
        if (!in_array($file->getClientOriginalExtension(), ['xls', 'xlsx'])) {
            throw new ApiException('文件后缀必须为 .xls');
        }

        return true;
    }

    /**
     * 去掉分页返回的多余值
     */
    public function removeNoUsedPageParams($data)
    {
        unset($data['first_page_url']);
        unset($data['from']);
        unset($data['last_page_url']);
        unset($data['next_page_url']);
        unset($data['path']);
        unset($data['prev_page_url']);
        unset($data['to']);
        unset($data['links']);

        return $data;
    }


}
